const Todo = require('../models/Todo');

// @desc    Get daily todo summary
// @route   GET /api/ai/daily-summary
// @access  Public
exports.getDailySummary = async (req, res, next) => {
  try {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    // 获取今天的任务
    const todayTodos = await Todo.find({
      createdAt: {
        $gte: today,
        $lt: tomorrow
      }
    });
    
    // 统计任务数量
    const totalTodos = todayTodos.length;
    const completedTodos = todayTodos.filter(todo => todo.completed).length;
    const pendingTodos = totalTodos - completedTodos;
    
    // 按优先级统计
    const highPriority = todayTodos.filter(todo => todo.priority === 'high').length;
    const mediumPriority = todayTodos.filter(todo => todo.priority === 'medium').length;
    const lowPriority = todayTodos.filter(todo => todo.priority === 'low').length;
    
    // 按分类统计
    const workTodos = todayTodos.filter(todo => todo.category === 'work').length;
    const studyTodos = todayTodos.filter(todo => todo.category === 'study').length;
    const lifeTodos = todayTodos.filter(todo => todo.category === 'life').length;
    
    // 生成总结文案
    let summary = `今天你创建了 ${totalTodos} 个任务`;
    if (completedTodos > 0) {
      summary += `，完成了 ${completedTodos} 个`;
    }
    
    // 添加优先级提醒
    if (highPriority > 0) {
      summary += `，其中有 ${highPriority} 个高优先级任务需要特别关注`;
    }
    
    // 添加分类建议
    if (workTodos > 0 && studyTodos > 0) {
      summary += '，工作和学习任务并重，请合理安排时间';
    } else if (workTodos > 0) {
      summary += '，专注于工作相关任务';
    } else if (studyTodos > 0) {
      summary += '，专注于学习相关任务';
    }
    
    res.status(200).json({
      success: true,
      data: {
        summary,
        stats: {
          total: totalTodos,
          completed: completedTodos,
          pending: pendingTodos,
          priority: {
            high: highPriority,
            medium: mediumPriority,
            low: lowPriority
          },
          category: {
            work: workTodos,
            study: studyTodos,
            life: lifeTodos
          }
        }
      }
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Get smart sort suggestions
// @route   GET /api/ai/smart-sort
// @access  Public
exports.getSmartSort = async (req, res, next) => {
  try {
    // 获取所有未完成的任务
    const pendingTodos = await Todo.find({ completed: false });
    
    // 智能排序建议
    const suggestions = [];
    
    // 1. 紧急任务建议（高优先级且接近截止日期）
    const urgentTodos = pendingTodos.filter(todo => {
      return todo.priority === 'high' && 
             todo.dueDate && 
             new Date(todo.dueDate) < new Date(Date.now() + 24 * 60 * 60 * 1000);
    });
    
    if (urgentTodos.length > 0) {
      suggestions.push({
        type: 'urgent',
        message: `你有 ${urgentTodos.length} 个紧急任务需要优先处理`,
        todos: urgentTodos.map(todo => ({
          id: todo._id,
          title: todo.title,
          dueDate: todo.dueDate
        }))
      });
    }
    
    // 2. 今日重点任务建议
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const todayTodos = pendingTodos.filter(todo => {
      return todo.dueDate && 
             new Date(todo.dueDate) >= today && 
             new Date(todo.dueDate) < tomorrow;
    });
    
    if (todayTodos.length > 0) {
      suggestions.push({
        type: 'today',
        message: `今天需要完成 ${todayTodos.length} 个任务`,
        todos: todayTodos.map(todo => ({
          id: todo._id,
          title: todo.title,
          priority: todo.priority
        }))
      });
    }
    
    // 3. 长期任务建议
    const longTermTodos = pendingTodos.filter(todo => {
      return todo.dueDate && 
             new Date(todo.dueDate) >= tomorrow;
    });
    
    if (longTermTodos.length > 0) {
      suggestions.push({
        type: 'long_term',
        message: `你有 ${longTermTodos.length} 个长期任务，可以合理分配到未来几天`,
        todos: longTermTodos.map(todo => ({
          id: todo._id,
          title: todo.title,
          dueDate: todo.dueDate
        }))
      });
    }
    
    // 4. 无截止日期任务建议
    const noDueDateTodos = pendingTodos.filter(todo => !todo.dueDate);
    
    if (noDueDateTodos.length > 0) {
      suggestions.push({
        type: 'no_due_date',
        message: `你有 ${noDueDateTodos.length} 个任务没有设置截止时间，建议为它们设置合理的时间`,
        todos: noDueDateTodos.map(todo => ({
          id: todo._id,
          title: todo.title
        }))
      });
    }
    
    res.status(200).json({
      success: true,
      data: {
        suggestions
      }
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Generate todo reminder message
// @route   POST /api/ai/generate-reminder
// @access  Public
exports.generateReminder = async (req, res, next) => {
  try {
    const { todoId } = req.body;
    
    if (!todoId) {
      return res.status(400).json({
        success: false,
        error: 'todoId is required'
      });
    }
    
    // 获取指定任务
    const todo = await Todo.findById(todoId);
    
    if (!todo) {
      return res.status(404).json({
        success: false,
        error: 'Todo not found'
      });
    }
    
    // 生成提醒文案
    let reminder = '';
    
    // 根据任务标题和描述生成个性化提醒
    if (todo.title) {
      reminder += `提醒：${todo.title}`;
    }
    
    if (todo.description) {
      reminder += ` - ${todo.description}`;
    }
    
    // 添加优先级提醒
    if (todo.priority === 'high') {
      reminder += ' ⚠️ 这是一个高优先级任务，请优先处理！';
    } else if (todo.priority === 'medium') {
      reminder += ' 💼 这是一个中等优先级任务，请适时处理。';
    } else {
      reminder += ' 📝 这是一个低优先级任务，可以稍后处理。';
    }
    
    // 添加截止时间提醒
    if (todo.dueDate) {
      const dueDate = new Date(todo.dueDate);
      const now = new Date();
      const timeDiff = dueDate - now;
      const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
      
      if (daysDiff < 0) {
        reminder += ` ⏰ 任务已过期 ${Math.abs(daysDiff)} 天，请尽快完成！`;
      } else if (daysDiff === 0) {
        reminder += ' ⏰ 任务今天到期，请务必完成！';
      } else if (daysDiff === 1) {
        reminder += ' ⏰ 任务明天到期，请提前准备！';
      } else {
        reminder += ` ⏰ 任务还有 ${daysDiff} 天到期，请合理安排时间。`;
      }
    }
    
    // 添加分类相关建议
    const categoryTips = {
      work: '💼 工作任务需要专注处理，建议安排在精力充沛的时间段完成。',
      study: '📚 学习任务需要持续投入，建议制定详细的学习计划。',
      life: '🏠 生活任务可以灵活安排，建议在空闲时间处理。'
    };
    
    if (categoryTips[todo.category]) {
      reminder += ` ${categoryTips[todo.category]}`;
    }
    
    res.status(200).json({
      success: true,
      data: {
        reminder,
        todo: {
          id: todo._id,
          title: todo.title,
          description: todo.description,
          priority: todo.priority,
          category: todo.category,
          dueDate: todo.dueDate
        }
      }
    });
  } catch (err) {
    next(err);
  }
};